package com.progroup.graphics;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.progroup.checks.Checks;
import com.progroup.kyrsmoney.R;
import com.progroup.kyrsmoney.database.DBAdapter;
import com.progroup.kyrsmoney.dialog.CustomDialog;
import com.progroup.kyrsmoney.preferences.PreferencesActivity;

public class ChartMini extends SherlockFragmentActivity {
	
	
	private GraphicalView BarChartView;
	CustomDialog  dialog;
	SharedPreferences pref;
	private String MONEY1="usd"; 
	private String MONEY2="buy";
	private int [] rtyq = {0,0};
	private String[] buy_sale; //= {"Покупка", "Продажа"};
	private String [] usd_eur; //= {"Доллар", "Евро", "Рубль"};
	private String USD_EUR_RUB = "";
	List<Date> dates;
	List<Double> values;
	private String name_bank;
	ActionBar actionbar = null;
	Spinner spinner1;
	Spinner spinner2;
	LinearLayout layout ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 setTheme(R.style.Theme_Sherlock);
		super.onCreate(savedInstanceState);
		Checks.ChartMini = Checks.KEYBACK_YES;
		buy_sale = new String[]{this.getText(R.string.graphic_buy).toString(), this.getText(R.string.graphic_sale).toString()};
		usd_eur = new String[]{getText(R.string.graphic_usd).toString(), getText(R.string.graphic_eur).toString(), getText(R.string.graphic_rub).toString()};
		
		actionbar = getSupportActionBar();
		Drawable myIcon = getResources().getDrawable( R.drawable.action_bar_fon);
		actionbar.setBackgroundDrawable(myIcon);
		
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		name_bank = getIntent().getStringExtra("name");
		USD_EUR_RUB = getIntent().getStringExtra("kypyra");
		setContentView(R.layout.graphics);
		
		pref = PreferenceManager.getDefaultSharedPreferences(this);
		
		layout= (LinearLayout) findViewById(R.id.liner);  
		spinner1 = (Spinner)findViewById(R.id.spinner1);
		spinner2 = (Spinner)findViewById(R.id.spinner2);
		ArrayAdapter<String> feat_adapter1 = new ArrayAdapter<String>(ChartMini.this, R.layout.spintext,  buy_sale);
		feat_adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner1.setAdapter(feat_adapter1);
		spinner1.setAdapter(feat_adapter1);
		ArrayAdapter<String> feat_adapter2 = new ArrayAdapter<String>(ChartMini.this, R.layout.spintext,  usd_eur);
		feat_adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner2.setAdapter(feat_adapter2);
		spinner1.setSelection(0);
		if(USD_EUR_RUB.equalsIgnoreCase("USD")){
			spinner2.setSelection(0);
		}else if(USD_EUR_RUB.equalsIgnoreCase("EUR")){
			spinner2.setSelection(1);
		}else if(USD_EUR_RUB.equalsIgnoreCase("RUB")){
			spinner2.setSelection(2);
		}
		
		
		rtyq[0]=spinner1.getSelectedItemPosition();
		rtyq[1]=spinner2.getSelectedItemPosition();
		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(rtyq[0]!=arg2){
					rtyq[0]=arg2;
					if(arg2==0){
						MONEY1="buy";
					}else{
						MONEY1="sale";
					}
					layout.removeAllViews();
					dialog = new CustomDialog(ChartMini.this, Checks.DIALOG_LOADING, null);
					dialog.show();
					new ParseSite().execute();
				}
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
			
		});
		spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(rtyq[1]!=arg2){
					rtyq[1]=arg2;
					if(arg2==0){
						MONEY2="usd";
					}else if(arg2==1){
						MONEY2="eur";
					}else{
						MONEY2="rub";
					}
					
					layout.removeAllViews();
					dialog= new CustomDialog(ChartMini.this, Checks.DIALOG_LOADING, null);
					dialog.show();
					new ParseSite().execute();
				}
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		
		if(spinner1.getSelectedItemPosition()==0){MONEY1="buy";};
		if(spinner1.getSelectedItemPosition()==1){MONEY1="sale";};
		if(spinner2.getSelectedItemPosition()==0){MONEY2="usd";};
		if(spinner2.getSelectedItemPosition()==1){MONEY2="eur";};
		if(spinner2.getSelectedItemPosition()==2){MONEY2="rub";};
		
		dialog = new CustomDialog(ChartMini.this, Checks.DIALOG_LOADING, null);
		dialog.show();
		new ParseSite().execute();
	}
	
	
	
	
	
	
	
	
	 public View ChartView(){
			
			XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
			XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
			mRenderer.setXTitle(getText(R.string.graphic_date).toString());
			//mRenderer.setYTitle("Координаты");
			mRenderer.setXAxisMin(dates.get(0).getTime());
			mRenderer.setXAxisMax(dates.get((dates.size()-1)).getTime());
			mRenderer.setYAxisMin(min()-0.1);
			mRenderer.setYAxisMax(max()+0.1);
			mRenderer.setAxesColor(Color.BLACK);//obvodka grafica
			mRenderer.setLabelsColor(Color.BLACK);//cvet teksta "Dati"
			mRenderer.setXLabelsColor(Color.BLACK);//cvet koordinat dati
			mRenderer.setYLabelsColor(0, Color.BLACK);
			
			
			
			mRenderer.setZoomButtonsVisible(true);
			
			
			
			
			mRenderer.setXLabels(10);
			mRenderer.setYLabels(10);
			mRenderer.setBackgroundColor(Color.WHITE);//cvet grafika v nytri!!
			mRenderer.setApplyBackgroundColor(true);
			//mRenderer.setMargins(new int[]{10,0,0,0}); //otstyp grafica ot kraev
			mRenderer.setMarginsColor(Color.WHITE);
			
			
			
			mRenderer.setYLabelsAlign(Align.RIGHT);
			
			
			
			
			mRenderer.setChartTitleTextSize(18);
			mRenderer.setLabelsTextSize(14);
			
			mRenderer.setAxisTitleTextSize(14);
			
			mRenderer.setLegendTextSize(14);
			
			
			
			//mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
			
			
			
			//mRenderer.setShowGrid(true); //setka
			//mRenderer.setGridColor(Color.LTGRAY);//cvet setki
			
			
			TimeSeries series1 = new TimeSeries(name_bank);
			XYSeriesRenderer renderer = new XYSeriesRenderer();
			
			if(BarChartView!=null){
				series1.clear();
			}
			
			renderer.setLineWidth(Integer.parseInt(pref.getAll().get(PreferencesActivity.LINE_WEIGTH)+""));
			
			if(BarChartView==null){
				
				for(int r = 0; r<dates.size(); r++)
				{
					
					if(values.get(r) != 0){
						series1.add(dates.get(r), values.get(r));
					}
				}
				mDataset.addSeries(series1);
				
				
				renderer.setColor(Color.GREEN);
				
				
				mRenderer.addSeriesRenderer(renderer);
			}else{
				
				for(int r = 0; r<dates.size(); r++)
				{
					if(values.get(r) != 0){
						series1.add(dates.get(r), values.get(r));
					}
				}
				mDataset.addSeries(series1);
				//Log.i("ElSE", series1.getX(i)+"="+series1.getY(i));
				
				
				renderer.setColor(Color.GREEN);
				
				
				mRenderer.addSeriesRenderer(renderer);
			}
			
			
			
			
			
			
			
			int length = mRenderer.getSeriesRendererCount();
			for (int i = 0; i < length; i++) {
				SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i);
				seriesRenderer.setChartValuesTextSize((float) ((Integer.parseInt(pref.getAll().get(PreferencesActivity.LINE_WEIGTH)+"")+12)*1.2));
				if(pref.getBoolean(PreferencesActivity.VISIBLE_COORDINAT, false)){
					seriesRenderer.setDisplayChartValues(true);
				}
			}
			
			
			
			if(BarChartView!=null){
				BarChartView.repaint();
			}
			
			
			BarChartView = ChartFactory.getTimeChartView(ChartMini.this, mDataset, mRenderer, "MM/dd");
			
			
			return BarChartView;
		}
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		layout.removeAllViews();
		new ParseSite().execute();
	}
	
	
	
	
	public void point_coordinat(){
		if(BarChartView!=null){
			values.clear();
		}
		DBAdapter dbHelper = new DBAdapter(ChartMini.this);
		dbHelper.open();
		Cursor cursor  = dbHelper.DB_CHART_GET_BANK_KYRS(name_bank,MONEY2, MONEY1);
		values = new ArrayList<Double>();
		if (cursor != null) {
			cursor.moveToFirst();
			int i = 0;
			do {
				values.add(Double.parseDouble(cursor.getString(0)));
				Log.e("POINT", (i++)+"");
			} while (cursor.moveToNext());
		}
		cursor.close();
		dbHelper.close();
		
	}
	
	
	public void KolichBankov(){
		DBAdapter dbHelper = new DBAdapter(ChartMini.this);
		dbHelper.open();
		
		Cursor cursor2  = dbHelper.DB_CHART_GET_DATA(2, name_bank);
		dates = new ArrayList<Date>();
		if (cursor2 != null) {
			cursor2.moveToFirst();
			int i = 0;
			do {
				dates.add(new Date(
						Integer.parseInt(cursor2.getString(0).substring(0, 4)), 
						Integer.parseInt(cursor2.getString(0).substring(4, 6))-1,
						Integer.parseInt(cursor2.getString(0).substring(6, 8))
						));
				Log.e("DATA", (i++)+"");
			} while (cursor2.moveToNext());
		}
		
		cursor2.close();
		dbHelper.close();
	}
	
	public double min(){
		double q = values.get(0);
		for(int i = 0; i<values.size(); i++)
		{
			
			if(q>values.get(i))
			{
				if(values.get(i)!=0){
					q=values.get(i);
				}
			}
			
		}
		return q;
	}
	
	public double max(){
		double q = values.get(0);
		for(int i = 0; i<values.size(); i++)
		{
			
			if(q<values.get(i))
			{
				q=values.get(i);
			}
			
		}
		return q;
	}
	
	
	private class ParseSite extends AsyncTask<String, Void, List<String>> {
		protected List<String> doInBackground(String... params) {
			try{
				KolichBankov();
				point_coordinat();
			}catch (Exception e) {
				// TODO: handle exception
				Log.e("CHARTMINI", e.toString());
			}
			
			return null;
		}
		protected void onPostExecute(List<String> output) {
			
				layout.addView(ChartView(), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
			
			try{
				dialog.dismiss();
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	
	
	
	
	
	 
	
	 @Override 
     public boolean onOptionsItemSelected(MenuItem item) 
     {
   	  switch (item.getItemId())
   	  {
   	  case android.R.id.home:
   	  {
   		 finish();
   		  break;
   		  }
   	  
   	  default: 
   		  return false; 
   	  }
   	  return super.onOptionsItemSelected(item); 
     }
     
	
	
	
	
	
}


